package com.wenbo.utils;


import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.util.concurrent.*;

/**
 * 线程相关工具类.
 *
 * @author ruoyi
 */
public class Threads {
    //private static final Logger logger = LoggerFactory.getLogger(Threads.class);

    // 核心线程池大小
    private static int corePoolSize = 5;

    // 最大可创建的线程数
    private static int maxPoolSize = 10;

    // 队列最大长度
    private static int queueCapacity = 50;

    // 线程池维护线程所允许的空闲时间
    private static int keepAliveSeconds = 60;
    /**
     * sleep等待,单位为毫秒
     */
    public static void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            //logger.debug("Interrupted!",e);
            Thread.currentThread().interrupt();
        }
    }

    /**
     * sleep等待,单位为毫秒
     */
    public static void wait(Object object,long timeout, int nanos) {
        try {
            object.wait(timeout,nanos);
        } catch (Exception e) {
            //logger.debug("Interrupted!",e);
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
    /**
     * sleep等待,单位为毫秒
     */
    public static void wait(Object object) {
        try {
            object.wait();
        } catch (Exception e) {
            //logger.debug("Interrupted!",e);
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    /**
     * sleep等待,单位为毫秒
     */
    public static void wait(Object object,long timeOut) {
        try {
            object.wait(timeOut);
        } catch (Exception e) {
            //logger.debug("Interrupted!",e);
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
    /**
     * 停止线程池
     * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
     * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
     * 如果仍人超時，則強制退出.
     * 另对在shutdown时线程本身被调用中断做了处理.
     */
    public static void shutdownAndAwaitTermination(ExecutorService pool) {
        if (pool != null && !pool.isShutdown()) {
            pool.shutdown();
            try {
                if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                    pool.shutdownNow();
                    if (!pool.awaitTermination(120, TimeUnit.SECONDS)) {
                        //logger.info("Pool did not terminate");
                    }
                }
            } catch (InterruptedException ie) {
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }

    /**
     * 打印线程异常信息
     */
    public static void printException(Runnable r, Throwable t) {
        if (t == null && r instanceof Future<?>) {
            try {
                Future<?> future = (Future<?>) r;
                if (future.isDone()) {
                    future.get();
                }
            } catch (CancellationException ce) {
                t = ce;
            } catch (ExecutionException ee) {
                t = ee.getCause();
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            //logger.error(t.getMessage(), t);
        }
    }

    public static ThreadPoolExecutor threadPoolExecutor() {

        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveSeconds,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueCapacity, true),
                new BasicThreadFactory.Builder().namingPattern("threadPoolExecutor-pool-%d").build(),
                new ThreadPoolExecutor.CallerRunsPolicy()) {
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                Threads.printException(r, t);
            }
        };

    }
}
